package org.jackysoft.security.config;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.util.SpringSecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.web.util.RedirectUrlBuilder;
import org.springframework.stereotype.Component;


@Component("casProcessingFilterEntryPoint")
public class MyCasAuthenticationEntryPoint extends CasAuthenticationEntryPoint {

	
	final static Log logger = LogFactory.getLog(MyCasAuthenticationEntryPoint.class);
	
	@Value("${cas.loginurl}")
	private String casLoginUrl;
	
	@Resource
	private ServiceProperties serviceProperties;
	
	@PostConstruct
	public void init(){
		this.setLoginUrl(casLoginUrl);
		this.setServiceProperties(serviceProperties);
	}
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.security.cas.web.CasAuthenticationEntryPoint#preCommence
	 * (javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void preCommence(HttpServletRequest request,
			HttpServletResponse response) {
		 String returnUrl = null;
		try {
			returnUrl = buildHttpReturnUrlForRequest(request);
		} catch (IOException e) {
			logger.error(e);
		} catch (ServletException e) {
			logger.error(e);
		}  
	    request.getSession().setAttribute(SpringSecurityUtils.VISITED_URL, returnUrl);  
	}

	protected String buildHttpReturnUrlForRequest(HttpServletRequest request)
			throws IOException, ServletException {

		RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
		urlBuilder.setScheme(request.getScheme());
		urlBuilder.setServerName(request.getServerName());
		urlBuilder.setPort(request.getServerPort());
		urlBuilder.setContextPath(request.getContextPath());
		urlBuilder.setServletPath(request.getServletPath());
		urlBuilder.setPathInfo(request.getPathInfo());
		urlBuilder.setQuery(request.getQueryString());
		return urlBuilder.getUrl();
	}

}
